/**
 * 附近门店
 * author:zhangjlt
 * date:2017年3月16日13:30:42
 */
;
define(function(require, exports, module) {
	var wechat = require("wechat");

	var nearShop = {
		stores: [],
		citycode:"",
		map: {},
		infowindow: {},
		currentPosition: {},
		/**
		 * bindEvent 页面事件
		 */
		bindEvent: function() {
			//返回
			$("#return_nearShop").unbind().on("click", function() {
				window.location.href = "#home";
			});
		},
		/**
		 * 进行页面路由监听配置 
		 */
		bindRout: function() {
			//公共页面监听路由
			Path.map("#/index/:page_name").to(function() {
				console.log(this.params["page_name"]);
				var page_name = this.params["page_name"];
				var nextPageFrom = "right"; //从右边过来
				//页面加载方向
				if(page_name == "nearShop" || page_name == "home" || page_name == "my") {
					nextPageFrom = "none";
				}
				//记录状态
				common.loadPage({
					pageUrl: "html/" + page_name + ".html",
					reload: true,
					from: nextPageFrom
				});
			});
			//会员中心的路由
			Path.map("#home").to(function() {
				//返回首页
				common.loadPage({
					pageUrl: "html/index.html",
					reload: false,
					from: "none"
				});
			});
			Path.listen();
		},
		/**
		 * 页面数据加载
		 */
		initData: function() {
			var height = document.documentElement.clientHeight - $(".header").height() - $(".pro_footer").height() - 10;
			if(common.isWeiXin()) {
				height += $(".header").height();
			}
			$("#container").height(height);

			nearShop.map = new AMap.Map('container', {
				resizeEnable: true,
				zoom: 10,
				center: [116.397428, 39.90923]
			});
			nearShop.map.plugin(['AMap.Geolocation', 'AMap.Scale', 'AMap.ToolBar'], function() { //添加定位控件
				var geolocation = new AMap.Geolocation({ //定位设置
					enableHighAccuracy: false, //是否使用高精度定位，默认:true
					convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true		 
					showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
					timeout: 10000, //超过10秒后停止定位，默认：无穷大
					buttonOffset: new AMap.Pixel(20, 50), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
					buttonPosition: 'LB'
				});
				scale = new AMap.Scale(); //添加比例尺控件
				toolbar = new AMap.ToolBar(); //添加工具栏控件
				nearShop.map.addControl(geolocation);
				nearShop.map.addControl(scale);
				nearShop.map.addControl(toolbar);
				geolocation.getCurrentPosition();
				geolocation.getCityInfo(function(status, result) {
					if(status=="complete"){
						nearShop.citycode = result.citycode;
					}else{
						nearShop.citycode ="010";
					}
				});

				AMap.event.addListener(geolocation, 'complete', function(res) {
					console.log(res);

					nearShop.map.setZoom(12);
					AMap.service('AMap.Circle', function() {

						var circle = new AMap.Circle({
							center: new AMap.LngLat(res.position.lng, res.position.lat), // 圆心位置
							radius: 5000, //半径
							strokeColor: "#72C4F6", //线颜色
							strokeOpacity: 0.9, //线透明度
							strokeWeight: 1,
							fillColor: "#72C4F6", //填充颜色
							fillOpacity: 0.35 //填充透明度
						});
						circle.setMap(nearShop.map);

					});
					nearShop.currentPosition = res.position;
					nearShop.loadData(res);
					//					nearShop.getAllStoresCallback();

				}); //返回定位信息
				AMap.event.addListener(geolocation, 'error', function(res) {
					console.log(res);
				}); //返回定位出错信息

			});
		},
		loadData: function(res) {
			if(res.status == 1) {
				var param = {
					longitude: res.position.lng,
					latitude: res.position.lat,
					radius: "10000"
				}
				console.log(param.toString());
				common.showLoading();
				common.loadData({
					url: "/wxmember/service/getAllStores",
					param: param,
					successCallBack: nearShop.getAllStoresCallback, //回调函数
					dataSource: "getWxUserInfo"
				});
			} else {
				common.showTip({
					content: "定位失败"
				});
			}
		},
		getAllStoresCallback: function(res) {
			if(res.status == "0") {
				nearShop.stores = res.data;
				if(res.data.length > 0) {
					var markers = [];
					for(var i = 0; i <res.data.length; i++) {
						var latitude = parseFloat(res.data[i].latitude);
						var longitude = parseFloat(res.data[i].longitude);
						var j = i+1;
						var icon = 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b' +j+ '.png';
						var item = {
							icon: icon,
							position: [longitude, latitude],
							turns:i
						}
						markers.push(item);
					}
					// 添加一些分布不均的点到地图上,地图上添加三个点标记，作为参照
					var objMarker = [];
					markers.forEach(function(marker) {
						var markerItem = new AMap.Marker({
							map: nearShop.map,
							icon: marker.icon,
							position: [marker.position[0], marker.position[1]],
							offset: new AMap.Pixel(-12, -36)
						});
						markerItem.content = marker.turns;
						markerItem.on('click', nearShop.markerClick);
						objMarker.push(markerItem);
					});
				} else {
					common.showTip({
						content: "您附近没有门店"
					});
				}
			} else {
				common.showTip({
					content: res.message
				});
			}
		},
		markerClick: function(e) {
			nearShop.initinfowidow(e.target.content);
			nearShop.infowindow.open(nearShop.map, e.target.getPosition());

		},
		initinfowidow: function(i) {
			
			//实例化信息窗体
			var title = nearShop.stores[i].name;
			var content = [];
			content.push("地址:"+nearShop.stores[i].address);
//			content.push("电话：010-64733333");

			AMap.service('AMap.InfoWindow', function() {
				var infoWindow = new AMap.InfoWindow({
					isCustom: true, //使用自定义窗体
					content: nearShop.createInfoWindow(title, content.join("<br/>")),
					offset: new AMap.Pixel(16, -45)
				});
				nearShop.infowindow = infoWindow;
			});
		},
		//构建自定义信息窗体
		createInfoWindow: function(title, content) {
			var info = document.createElement("div");
			info.className = "info";
			//可以通过下面的方式修改自定义窗体的宽高
			//info.style.width = "400px";
			// 定义顶部标题
			var top = document.createElement("div");
			var titleD = document.createElement("div");
			var closeX = document.createElement("img");
			top.className = "info-top";
			titleD.innerHTML = title;
			closeX.src = "http://webapi.amap.com/images/close2.gif";
			top.onclick = nearShop.closeInfoWindow;

			top.appendChild(titleD);
			top.appendChild(closeX);
			info.appendChild(top);

			// 定义中部内容
			var middle = document.createElement("div");
			middle.className = "info-middle";
			middle.style.backgroundColor = 'white';
			middle.innerHTML = content;
			info.appendChild(middle);

			var html = '<div class="amap-info-combo status-destination"><table>' +
				'<tr class="amap-info-tabs"><td class="tab selected"><i class="tab-icon icon-end"></i>到这里去</td></tr></table>' +
				'<table cellpadding="0"><tr><td><div class="nav-button"><span id="nav-drive" class="nav-icon nav-drive">驾车</span><span id="nav-bus" class="nav-icon nav-bus">公交</span><span id="nav-walk" class="nav-icon nav-walk">步行</span></div></td></tr></table></div>'
			var midBottom = document.createElement("div");
			midBottom.innerHTML = html;
			info.appendChild(midBottom);

			// 定义底部内容
			var bottom = document.createElement("div");
			bottom.className = "info-bottom";
			bottom.style.position = 'relative';
			bottom.style.top = '0px';
			bottom.style.margin = '0 auto';
			var sharp = document.createElement("img");
			sharp.src = "http://webapi.amap.com/images/sharp.png";
			bottom.appendChild(sharp);
			info.appendChild(bottom);
			info.onclick = nearShop.testBind;
			return info;
		},
		testBind: function(e) {
			var winPosition = nearShop.infowindow.getPosition();
			switch(e.target.id) {
				case "nav-drive":
					nearShop.drive(winPosition);
					break;
				case "nav-bus":
					nearShop.bus(winPosition);
					break;
				case "nav-walk":
					nearShop.walk(winPosition);
					break;
				default:
					break;
			}
		},
		//关闭信息窗体
		closeInfoWindow: function() {

			nearShop.map.clearInfoWindow();
		},
		drive: function(position) {
			$("#panel").html("");
			nearShop.map.clearMap();
			AMap.service('AMap.Driving', function() {
				var driving = new AMap.Driving({
					map: nearShop.map,
					panel: "panel"
				});
				// 根据起终点经纬度规划驾车导航路线
				var start = new AMap.LngLat(nearShop.currentPosition.lng, nearShop.currentPosition.lat);
				var zhongdian = new AMap.LngLat(position.lng, position.lat);
				driving.search(start, zhongdian, function(status, result) {
					console.log(result);
				});
			});
		},
		walk: function(position) {
			$("#panel").html("");
			nearShop.map.clearMap();
			AMap.service('AMap.Walking', function() {
				var walking = new AMap.Walking({
					map: nearShop.map,
					panel: "panel"
				});
				
				var start = new AMap.LngLat(nearShop.currentPosition.lng, nearShop.currentPosition.lat);
				var zhongdian = new AMap.LngLat(position.lng, position.lat);
				// 根据起终点经纬度规划不行导航路线
				walking.search(start, zhongdian, function(status, result) {
					console.log(result);
				});
			});
		},
		bus: function(position) {
			$("#panel").html("");
			nearShop.map.clearMap();
			AMap.service('AMap.Transfer', function() {
				var transfer = new AMap.Transfer({
					map: nearShop.map,
					panel: "panel"
				});
				transfer.setCity(nearShop.citycode);
				var start = new AMap.LngLat(nearShop.currentPosition.lng, nearShop.currentPosition.lat);
				var zhongdian = new AMap.LngLat(position.lng, position.lat);
				// 根据起终点经纬度规划公交导航路线
				transfer.search(start, zhongdian, function(status, result) {
					console.log(result);
				});
			});
		},

		/**
		 * each page init mothed
		 */
		initialize: function() {
			var _this = this;
			/*//动态加载数据
			$script("http://cache.amap.com/lbs/static/es5.min.js", function() {
				$script("http://webapi.amap.com/maps?v=1.3&key=bf1b6e6dbd9477b2386f51f9919ae856", function() {
					$script("http://cache.amap.com/lbs/static/addToolbar.js", function() {
						$(document).ready(function(){
							_this.initData();
						});
					});
				});
			});*/
			//map加载完成
			$script.ready('mapJs', function() {
				_this.initData();
			})
			//事件绑定
			this.bindEvent();
			//路由绑定
			this.bindRout();
		}
	};
	module.exports = nearShop;
});